package com.cmcc.sdtp.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.cmcc.sdtp.util.SdtpPropertiesUtil;


public class SDTPServer implements Runnable {
	
	private static final Logger logger = LogManager.getLogger(SDTPServer.class);
	private SDTPServer(){}
	
	private static final SDTPServer server = new SDTPServer();
	
	private static List<SDTPRequestThread> requestThredList = new ArrayList<SDTPRequestThread>();

	public static final int SERVER_PORT = Integer.valueOf(SdtpPropertiesUtil
			.getProperty("LOCALHOST_SERVER_PORT"));
	private ServerSocketChannel serverSocketChannel;
	
	public static volatile boolean sdtpFlag = false;
	public void run() {
		optNio();
	}

	
	public void optNio(){
		System.out.println("Sdtp server start.....");
        if(sdtpFlag==false){//上一次的sdtp状态
        	sdtpFlag = true; //打开连接
        	try {
				serverSocketChannel = ServerSocketChannel.open();
				serverSocketChannel.socket().bind(new InetSocketAddress(SERVER_PORT));
			}catch (IOException e) {
				try {
					if (serverSocketChannel != null) {
						serverSocketChannel.close();
					}
				} catch (IOException e1) {
				}	
				return;
			}
			while (sdtpFlag) {
				try {
					SocketChannel socketclient = serverSocketChannel.accept();
					SDTPRequestThread requestThred = new SDTPRequestThread(socketclient);
					synchronized (requestThredList) {
						if(sdtpFlag)
						{
							new Thread(requestThred).start();
							requestThredList.add(requestThred);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}	
			} 
        }else {
            sdtpFlag = false;
            //关闭channel,清空dpiMap
            if (serverSocketChannel != null) {
				try {
					serverSocketChannel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
            Map<String, String> dpiMap = SDTPRequestThread.dpiMap;
            dpiMap.clear();
            
            synchronized(requestThredList)
            {
            	Iterator<SDTPRequestThread> it = requestThredList.iterator();
            	while(it.hasNext())
            	{
            		it.next().release();
            		it.remove();
            	}
            }
            
        }
 }
	
	public static SDTPServer getInstall(){
		return server;
	}

}